import server from '@dt/server/dt'

const api = {
  upload: () => server.api().upload('/api/v1/oss/upload') //单图片
}

function upload(file) {
  return api.upload().fetch({ modelName: 'asset', file, fileName: 'file' })
}

function chooseImage() {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      sizeType: 'compressed',
      count: 1,
      success(res) {
        if (res.tempFiles) {
          let file = res.tempFiles[0]
          if (file.size > 5000000) {
            uni.showToast({
              icon: 'none',
              title: '图片过大'
            })
            reject(new Error('图片过大'))
          } else {
            console.log(file)
            resolve(file.path)
          }
        }
      },
      fail: reject
    })
  })
}

function chooseImages(opt) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      sizeType: opt?.sizeType || ['compressed'],
      count: opt?.count || 9,
      sourceType: opt?.sourceType || ['album'],
      extension: ['.png', '.jpg', '.jpeg', '.PNG', '.JPG', '.JPEG'],
      success(res) {
        if (
          res.tempFilePaths?.length &&
          !res.tempFilePaths.some((item) => {
            const extension = item.split('.').pop()
            const arr = ['jpg', 'png', 'jpeg', 'PNG', 'JPG', 'JPEG'] // 允许的图片格式列表
            if (item.size > 1024 * 1024 * 50) {
              uni.showToast({
                icon: 'none',
                title: '图片过大'
              })
              reject(new Error('图片过大'))
              return true
            } else if (extension && !arr.includes(extension)) {
              reject(new Error('图片格式仅支持JPG、PNG、JPEG'))
              uni.showToast({ title: '图片格式仅支持JPG、PNG、JPEG', icon: 'none' })
              return true
            }
          })
        ) {
          resolve(res.tempFilePaths)
        }
      },
      fail: (err) => reject(new Error(err))
    })
  })
}

export default {
  chooseImage,
  upload,
  chooseImages
}
